//
//  EditMainCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class EditMainCell: UITableViewCell {

    // MARK: - Outlets

    private lazy var separatorView = CellSeparator()
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 17, weight: .bold)
        lbl.textAlignment = .left
        lbl.sizeToFit()
        lbl.textColor = .black
        lbl.text = "Характеристики"
        return lbl
    }()
    
    private lazy var mainStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fillProportionally
        stack.spacing = 12
        return stack
    }()
    
    private lazy var priceField: ModalElement = {
        let element = ModalElement()
        element.updateUI(value: nil, placeholder: "Цена", withTF: true, keyboardType: .numberPad)
        element.snp.makeConstraints { (make) in
            make.height.equalTo(48)
        }
        return element
    }()
    
    private lazy var ruleField: ModalElement = {
        let btn = ModalElement()
        btn.updateUI(value: nil, placeholder: ModalView.ModalType.rule.rawValue)
        btn.modal = ModalView.ModalType.rule
        btn.delegate = self
        btn.snp.makeConstraints { (make) in
            make.height.equalTo(48)
        }
        return btn
    }()
    
    private lazy var rastomozhenToggle: ToggleView = {
        let view = ToggleView()
        view.makeToggleView(name: "Растаможен", isOn: false)
        view.snp.makeConstraints { (make) in
            make.height.equalTo(64)
        }
        return view
    }()
    
    private lazy var obmenToggle: ToggleView = {
        let view = ToggleView()
        view.makeToggleView(name: "Возможен обмен", isOn: false)
        view.snp.makeConstraints { (make) in
            make.height.equalTo(64)
        }
        return view
    }()
    
    
    private var ruleType: RuleType!
    
    @objc private func getRuleUpdate (notification: NSNotification) {
        if let userInfo = notification.userInfo {
            if let type = userInfo["type"] as? ModalView.ModalType, type == .rule {
                if let data = userInfo["data"] as? [ModalView.ModalData], data.count == 1 {
                    ruleType = RuleType(value: data[0].id!, display: data[0].name)
                    self.ruleField.updateUI(value: data[0].name)
                }
            }
        }
    }
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
        NotificationCenter.default.addObserver(self, selector: #selector(getRuleUpdate(notification:)), name: NSNotification.Name(rawValue: "sendEditModal"), object: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "sendEditModal"), object: nil)
    }
}

extension EditMainCell: ConfigurableCell {
    
    func configure(data object: EditViewModel.EditMainItem, index: Int) {
        self.ruleType = object.rule
        self.ruleField.updateUI(value: object.rule?.display)
        
        self.obmenToggle.changeValue(to: object.isObmen)
        
        self.rastomozhenToggle.changeValue(to: object.rastomozhen)
        
        if let price = object.price {
            self.priceField.setTextFieldText("\(price)")
        }
    }

    func returnData() -> EditViewModel.EditMainItem {
        return EditViewModel.EditMainItem(price: Int(self.priceField.getTextFieldValue()),
                                          rule: self.ruleType,
                                          rastomozhen: self.rastomozhenToggle.isOn(),
                                          isObmen: self.obmenToggle.isOn())
    }
}

extension EditMainCell: ModalElementProtocol {
    func selectElement(modal: ModalView.ModalType?, customID: Int?) {
        NotificationCenter.default.post(name: NSNotification.Name("openEditModal"), object: nil, userInfo: ["modal": modal as Any, "clear": false])
    }
    
    func didClear(modal: ModalView.ModalType) {
        //
    }
}



extension EditMainCell {
    
    private func addViews () {
        self.contentView.addSubview(separatorView)
        contentView.addSubview(mainStack)
        contentView.addSubview(titleLbl)
        
        mainStack.addArrangedSubview(priceField)
        mainStack.addArrangedSubview(ruleField)
        mainStack.addArrangedSubview(rastomozhenToggle)
        mainStack.addArrangedSubview(obmenToggle)
        
        titleLbl.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(22)
            make.height.equalTo(20)
        }
        mainStack.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(titleLbl.snp.bottom).offset(18)
            make.bottom.equalTo(separatorView.snp.top).offset(-16)
        }
        
        separatorView.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(20)
        }
    }
}

